{% load i18n %}
<script>
    // 取order
    $(document).ready(function() {
        $(".nav-title ul a li").removeClass("active");
        $("#nav_trade").addClass("active")
        // 加载order
        on_login();
        set_timer()
    })

    function init_limit_from_ready()
    {
        $("#buy_price,#buy_count").change(function(){
            $("#buy_msg").html("&nbsp;");
            return;
        });

        // 价格改变
        $("#buy_price").keyup(function(){
            on_buy_price_change();
        })

        $("#buy_count").keyup(function(){
            on_buy_count_change(s1)
        });

        $("#buy_amount").keyup(function(){
            on_buy_amount_change(s1)
        });

        // 价格改变
        $("#sell_price").keyup(function(){
            on_sell_price_change();
        })

        $("#sell_count").keyup(function(){
            on_sell_count_change(s2)
        });

        $("#sell_use_amount").keyup(function(){
            on_sell_use_amount_change(s2)
        });

        //购买按钮
        $("#buy_button").click(function()
        {
            on_buy_click();
        });

        $("#sell_button").click(function()
        {
            on_sell_click();
        });

        var s1 = $("#h-slider").slider({
            orientation: "horizontal",
            range: "min",
            min: 0,
            max: 100,
            value: 60,
            slide: function (event, ui) {
                buy_slider_change(ui.value)
                $("#buy_msg").html("&nbsp;");
            }
        });

        var s2 = $("#h-slider2").slider({
            orientation: "horizontal",
            range: "min",
            min: 0,
            max: 100,
            value: 0,
            slide: function (event, ui) {
                sell_slider_change(ui.value)
                $("#sell_msg").html("&nbsp;");
            }
        });

        $("#sell_count").change(function(){
            buy_val = $("#sell_count").val()
            curr_val = s2.slider("value")
            if (!(buy_val == curr_val))
            {
                s2.slider("value", buy_val)
            }
        });
    }

    function init_market_from_ready()
    {
        //购买按钮
        $("#market_buy_button").click(function() {
            on_buy_market_click();
        });
        //卖出按钮
        $("#market_sell_button").click(function() {
            on_sell_market_click();
        });
        init_h_slider_3()
        init_h_slider_4()
    }

    function on_buy_market_click()
    {
        if (!$("#market_buy_amount").val() || $("#market_buy_amount").val() <= 0)
        {
            msg_tips("<b>{% trans '请输入大于0的数量' %}</b>", 3000);
            return
        }
        var buy_amount = $("#market_buy_amount").val()
        var total = parseInt( $("#buy_use_amount").html())
        if (total < buy_amount)
        {
            msg_tips("<b>{% trans '买入金额大于余额' %}</b>", 3000);
            return
        }

        var amount = $("#market_buy_amount").val()
        var market_key = g_coin0 + "2" + g_coin1
        var min_amount = g_markets[market_key].min_buy_amount
        if (amount < min_amount)
        {
            msg_tips("{% trans '最低买入数量为' %}: <b class='red'>" +min_amount+ "</b> {% trans '请修改后重试' %}", 3000);
            return
        }

        bootbox_market_buy()
    }

    function on_buy_market_change()
    {
        s1.slider("value", percent)
    }

    function init_h_slider_3()
    {
        var s3 = $("#h-slider3").slider({
            orientation: "horizontal",
            range: "min",
            min: 0,
            max: 100,
            value: 0,
            slide: function (event, ui) {
                buy_market_slider_change(ui.value)
                $("#sell_msg").html("&nbsp;");
            }
        });

        $("#market_buy_amount").keyup(function(){
            if (!g_auth){
                return
            }
            var total = parseInt($("#buy_use_amount").html())
            if (total <= 0)
                return
            var buy_amount = $("#market_buy_amount").val()
            var buy_val = buy_amount * 100 / total
            var curr_val = s3.slider("value")
            if (buy_val > 100)
            {
                buy_val = 100
            }

            if (!(buy_val == curr_val))
            {
                var buy_val = buy_val.toFixed(2)
                $("#buy_market_percent").html(buy_val+"%")
            }
        });
    }

    function init_h_slider_4()
    {
        var s4 = $("#h-slider4").slider({
            orientation: "horizontal",
            range: "min",
            min: 0,
            max: 100,
            value: 0,
            slide: function (event, ui) {
                sell_market_slider_change(ui.value)
                $("#sell_msg").html("&nbsp;");
            }
        });

        $("#sell_market_count").keyup(function(){
            if (!g_auth)
            {
                return
            }
            var total = parseInt($("#sell_amount").html())
            if (total <= 0)
                return
            var sell_amount = $("#sell_market_count").val()
            var sell_val = sell_amount * 100 / total
            if (sell_val > 100)
            {
                sell_val = 100
            }
            var curr_val = s4.slider("value")

            if (!(sell_val == curr_val))
            {
                var sell_val = sell_val.toFixed(2)
                $("#sell_market_percent").html(sell_val+"%")
            }
        });
    }

    function floor_input(key, tofixed)
    {
        //console.log("key %s %s" , key, tofixed)
        var val = $(key).val()
        var reg = new RegExp("^\\d*\.\\d{"+tofixed+"}\\w+$");
        if (reg.test(val))
        {
            val = floor_number(val, tofixed)
        }
        $(key).val(val)
    }

    function set_buy_amount(buy_price, buy_count)
    {
        var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
        buy_amount = buy_price * buy_count
        buy_amount = floor_number(buy_amount, tofixed1)
        $("#buy_amount").val(buy_amount)
    }

    // buy form ctrol begin {
        // 价格或者其他改变
        function on_buy_price_change()
        {
            var tofixed0 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
            if (!g_auth){
                return
            }
            floor_input("#buy_price", tofixed1)
            var buy_price = $("#buy_price").val()

            $("#buy_price").val(buy_price)
            if (buy_price <= 0)
            {
                return
            }
            //    console.log("buy_price " + buy_price)
            display_buy_price = buy_price * g_ExRate
            display_buy_price = display_buy_price.toFixed(tofixed1)
            $("#display_buy_price").val(display_buy_price)

            s1 = $("#h-slider").slider()
            var curr_amount = $("#buy_use_amount").html()
            var buy_count = $("#buy_count").val()
            if(buy_count > 0) {
                on_buy_count_change(s1)
                return
            }
            var buy_count = curr_amount / buy_price
            buy_count = floor_number(buy_count, tofixed0);
            $("#buy_count").val(buy_count)
            set_buy_amount(buy_price, buy_count)
            on_buy_count_change(s1)
        }

        function buy_slider_change(value)
        {
            if (!g_auth)
            {
                return
            }
            $("#buy_percent").html(value+"%")
            var curr_amount = $("#buy_use_amount").html()
            if (curr_amount <= 0)
            {
                return
            }
            var buy_price = $("#buy_price").val()
            if (buy_price=="")
            {
                return
            }
            //console.log("buy_price " + buy_price)
            if (!buy_price || buy_price <= 0)
            {
                buy_price = Number($("#curr_price").html())
            }
            $("#buy_price").val(buy_price)

            // 总量
            var count = curr_amount / buy_price

            // 100
            var buy_count = count * value / 100
            var tofixed0 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
            var buy_amount = floor_number(buy_count * buy_price, tofixed1)
            buy_count = floor_number(buy_count, tofixed0)

            $("#buy_count").val(buy_count)
            $("#buy_amount").val(buy_amount)
        }

        function buy_market_slider_change(value)
        {
            if (!g_auth)
            {
                return
            }
            $("#buy_market_percent").html(value+"%")
            var curr_amount = parseInt($("#buy_use_amount").html())
            if (curr_amount <= 0)
                return

            // 总量
            var buy_amount =  curr_amount * value / 100
            var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
            var buy_amount = floor_number(buy_amount, tofixed1)

            $("#market_buy_amount").val(buy_amount)

        }

        function on_buy_count_change(s1)
        {
            if (!g_auth)
            {
                return
            }

            var tofixed0 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            floor_input("#buy_count", tofixed0)
            var buy_count = $("#buy_count").val()
            var curr_amount = parseInt($("#buy_use_amount").html())
            var buy_price = $("#buy_price").val()
            var count = curr_amount / buy_price
            count = floor_number(count, tofixed0);
            if (buy_count > count)
            {
                //alert("count " + buy_count)
                $("#buy_count").val(count)
                $("#buy_percent").html("100%");
                $("#buy_msg").html("{% trans '数量过大' %}");
                return
            }
            //console.log("buy count" + buy_count)
            var percent = (buy_count/count) * 100
            percent = floor_number(percent, 2);
            //console.log("percent" + percent)

            var curr_val = floor_number(s1.slider("value"),0)
            //console.log("curr_val" + curr_val)
            if (!(percent == curr_val))
            {
                if (!isNaN(percent))
                {
                    s1.slider("value", percent)
                    $("#buy_percent").html(percent+"%");
                }
            }
            set_buy_amount(buy_price, buy_count)
        }

        function on_buy_amount_change(s1)
        {
            if (!g_auth)
            {
                return
            }
            var tofixed_amount = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
            floor_input("#buy_amount", tofixed_amount)
            var buy_amount = $("#buy_amount").val()
            var curr_amount = Number($("#buy_use_amount").html())
            if (buy_amount > curr_amount)
            {
                //console.log("curr_amount "  + curr_amount + " < buy_amount "  + buy_amount)
                //$("#buy_msg").html("金额超出最大值");
                buy_amount = curr_amount
                $("#buy_amount").val(buy_amount)
            }

            var buy_price = $("#buy_price").val()
            if (buy_price <= 0)
            {
                return
            }
            var count = curr_amount / buy_price
            var tofixed_count = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            count = floor_number(count, tofixed_count);

            var buy_count = buy_amount / buy_price
            var buy_count = floor_number(buy_count, tofixed_count);
            //console.log("buycount" + buy_count + " count" + count + "buy amount" + buy_amount)
            var percent = (buy_count/count) * 100
            percent = floor_number(percent,2);
            $("#buy_count").val(buy_count)
            if (!isNaN(percent))
            {
                s1.slider("value", percent)
                $("#buy_percent").html(percent+"%");
            }
        }

    // buy form ctrol end }
    //
    // sell form ctrol begin {
        // 价格或者其他改变
        function on_sell_price_change()
        {
            var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
            var tofixed_amount = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
            if (!g_auth)
            {
                return
            }
            floor_input("#sell_price", tofixed1)
            var sell_price = $("#sell_price").val()
            if (sell_price < 0)
            {
                $("#sell_price").val(0)
                return
            }

            // todo 显示
            display_sell_price = sell_price * g_ExRate
            display_sell_price = display_sell_price.toFixed(tofixed1)
            $("#display_sell_price").val(display_sell_price)

            var curr_amount = Number($("#sell_amount").html())
            var sell_count = $("#sell_count").val()
            s2 = $("#h-slider2").slider()
            if (sell_count == 0)
            {
                sell_count = curr_amount
                $("#sell_count").val(sell_count)
                on_sell_count_change(s2)
            }
            else
            {
                sell_use_amount = sell_price * sell_count
                sell_use_amount = floor_number(sell_use_amount, tofixed_amount)
                on_sell_count_change(s2)
                $("#sell_use_amount").val(sell_use_amount)
            }
        }

        function sell_slider_change(value)
        {
            if (!g_auth)
            {
                return
            }
            $("#sell_percent").html(value+"%")
            var curr_amount = Number($("#sell_amount").html())
            if (curr_amount <= 0)
            return

            var sell_price = $("#sell_price").val()
            if (sell_price <= 0)
            {
                sell_price = Number($("#curr_price").html())
                $("#sell_price").val(sell_price)
            }

            // 100
            var sell_count = (curr_amount / 100) * value
            var tofixed_count = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            var tofixed_amount = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
            sell_count = floor_number(sell_count, tofixed_count)
            var sell_use_amount = floor_number(sell_count * sell_price, tofixed_amount)

            $("#sell_count").val(sell_count)
            //alert("set stull use amount" + sell_use_amount)
            $("#sell_use_amount").val(sell_use_amount)
        }

        function sell_market_slider_change(value)
        {
            if (!g_auth)
            {
                return
            }
            $("#sell_market_percent").html(value+"%")
            var curr_amount = parseInt($("#sell_amount").html())
            if (curr_amount <= 0)
                return

            // 总量
            var sell_amount =  curr_amount * value / 100
            var tofixed1 = coin_tofixed(g_coin0, g_coin0, coin_tofixed_type_amount)
            var sell_amount = floor_number(sell_amount, tofixed1)

            $("#sell_market_count").val(sell_amount)

        }

        function on_sell_count_change(s1)
        {
            if (!g_auth)
            {
                return
            }
            var tofixed_count = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            floor_input("#sell_count", tofixed_count)

            var sell_count = $("#sell_count").val()
            var curr_amount = Number($("#sell_amount").html())
            var sell_price = $("#sell_price").val()
            //alert("sell count" + sell_count)
            //alert("curr count" + curr_amount)
            if (sell_count > curr_amount)
            {
                //alert("count " + sell_count +  " > curr amount " + curr_amount)
                $("#sell_count").val(curr_amount)
                $("#sell_percent").html("100%");
                $("#sell_msg").html("{% trans '数量过大' %}");
                return
            }
            //alert("sell count" + sell_count)
            var sell_use_amount = sell_count * sell_price
            sell_use_amount = floor_number(sell_use_amount,4)
            $("#sell_use_amount").val(sell_use_amount)

            var percent = (sell_count/curr_amount) * 100
            var curr_val = floor_number(s1.slider("value"),0)
            if (!(percent == curr_val))
            {
                if (!isNaN(percent))
                {
                    s1.slider("value", percent)
                    $("#sell_percent").html(percent+"%");
                }
            }
        }

        function on_sell_use_amount_change(s1)
        {
            if (!g_auth)
            {
                return
            }
            var tofixed_amount = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_amount)
            floor_input("#sell_use_amount", tofixed_amount)
            var sell_amount = $("#sell_use_amount").val()
            var curr_amount = parseFloat($("#sell_amount").html())
            var sell_price = $("#sell_price").val()
            if (sell_price <= 0)
            {
                sell_price = Number($("#curr_price").html())
                $("#sell_price").val(sell_price)
            }

            var can_sell_amount = sell_price * curr_amount
            can_sell_amount = floor_number(can_sell_amount, tofixed_amount)
            if (sell_amount > can_sell_amount)
            {
                //$("#sell_msg").html("金额超出最大值");
                sell_amount = can_sell_amount
                $("#sell_use_amount").val(can_sell_amount)
            }

            var sell_count = sell_amount / sell_price
            var tofixed_count = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            sell_count = floor_number(sell_count, tofixed_count);
            var percent = (sell_count/curr_amount) * 100
            percent = floor_number(percent, 2)
            if (!isNaN(percent))
            {
                s1.slider("value", percent)
                $("#sell_percent").html(percent+"%");
            }
            $("#sell_count").val(sell_count);
        }

        // sell form ctrol end }

    function on_login()
    {
        init_depths()
        //init_markets()
        init_curr_markets()
        init_trade_form('market')

        if (g_auth)
        {
            on_auth_login()
        }
        else
        {
            get_order_list_not_login()
        }
        get_all_order();
        get_last_trade();
        get_curr_market()
        get_market_left()
        init_inlink_svg()
    }

    function on_auth_login()
    {
        get_order_list();
        get_buy_amount();
        get_sell_amount();
    }

    function get_buy_amount()
    {
        get_amount(g_coin1, "#buy_use_amount");
    }

    function get_sell_amount()
    {
        get_amount(g_coin0, "#sell_amount");
    }

    // 买入
    function on_buy_click()
    {
        // todo 判断价格是否低于当前10%，如果低于，就显示输入框提示(取消或者继续)
        if (!$("#buy_price").val()||$("#buy_price").val() <= 0)
        {
            $("#buy_msg").html("{% trans '价格为空'%}");
            return;
        }
        // 判断是否大于当前
        if (!$("#buy_count").val() || $("#buy_count").val() <= 0)
        {
            $("#buy_msg").html("{% trans '买入数量不对' %}");
            return;
        }

        var amount = $("#buy_amount").val()
        var market_key = g_coin0 + "2" + g_coin1
        var min_amount = g_markets[market_key].min_buy_amount
        if (amount < min_amount)
        {
            msg_tips("{% trans '最低买入数量为' %}: <b class='red'>" +min_amount+ "</b> {% trans '请修改后重试' %}", 3000);
            return
        }

        bootbox_buy()
    }

    function bootbox_buy()
    {
        var buy_price = $("#buy_price").val()
        var buy_count = $("#buy_count").val()
        var buy_amount = $("#buy_amount").val()
        buy_amount = Calculate.CommaFormattedOnly(buy_amount)
        var coin_type = g_coin0
        var message = "{% trans '买入价格' %}:<b class=red>" + buy_price + "</b>, \
        {% trans '买入数量' %}:<b class=red>" + buy_count + "</b>, \
        {% trans '总价' %}:<b class=red>" + buy_amount + "</b>"
        bootbox.confirm({
            title: "{% trans '买入确认'%}",
            message: message,
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> {% trans "取消买入" %}'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> {% trans "确认买入" %}'
                }
            },
            callback: function (result) {
                if (result == true)
                {
                    verify_msm_buy()
                }
                //console.log('This was logged in the callback: ' + result);
            }
        });
    }

    function verify_msm_buy()
    {
        // 检查权限,如果成功就发送
        verify_msm('buy', buy_verify_callback)
    }

    function buy_verify_callback(result)
    {
        if (result)
        {
            send_buy()
        }
    }

    function send_buy()
    {
        //发送数据
        $.post("/btc/buy",
        $("#buy_form").serialize(),
        function(data){
            var result = data.result
            if (result == true)
            {
                msg_tips("<b>{% trans '操作成功' %}</b>", 3000);
                $("#buy_count").empty();
                get_buy_amount();
                get_order_list();
                get_order_history();
            }
            else if(result == false)
            {
                msg_tips("<b>{% trans '操作失败' %}</b>", 3000);
                $("#buy_msg").html("{% trans '操作失败' %}");
            }
            else
            {
                msg_tips("<b>{% trans '操作失败' %}</b>", 3000);
                $("#buy_msg").html("{% trans '操作失败' %}");
            }
        });
        $("#buy_count").val(0);
    }

    function bootbox_market_buy()
    {
        var buy_amount = $("#market_buy_amount").val()
        buy_amount = Calculate.CommaFormattedOnly(buy_amount)
        var coin_type = g_coin0
        var use_coin_type = g_coin1
        var message = " {% trans '买入金额' %}:<b class=red>" + buy_amount +"</b>"
        bootbox.confirm({
        title: "    <b>{% trans '市价买入确认'%}</b>",
            message: message,
            //size: 'small',
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> {% trans "取消买入" %}'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> {% trans "确认买入" %}'
                }
            },
            callback: function (result) {
                if (result == true)
                {
                    verify_msm_buy_market()
                }
                //console.log('This was logged in the callback: ' + result);
            }
        });
    }

    function verify_msm_buy_market()
    {
        // 检查权限,如果成功就发送
        verify_msm('buy', buy_market_verify_callback)
    }

    function buy_market_verify_callback(result)
    {
        if (result) {
            send_market_buy()
        }
    }

    function send_market_buy()
    {
        //发送数据
        $.post("/btc/buy",
        $("#buy_market_form").serialize(),
        function(result){
            if (result =="0")
            {
                msg_tips("<b>{% trans '市价买入操作成功' %}</b>", 3000);
                $("#buy_count").empty();
                get_buy_amount();
                get_order_list();
                get_order_history();
            }
            else if(result == 2)
            {
                msg_tips("<b>{% trans '操作失败' %}</b>", 3000);
                $("#buy_msg").html("{% trans '操作失败' %}");
            }
            else
            {
                msg_tips("<b>{% trans '操作失败' %}</b>", 3000);
            }
        });
        $("#buy_count").val(0);
    }

    // 卖出
    function on_sell_click()
    {
        //alert("========== " + $("#buy_use_amount").html())
        // todo 判断价格是否低于当前10%，如果低于，就显示输入框提示(取消或者继续)
        if (!$("#sell_price").val()||$("#sell_price").val() <= 0)
        {
            $("#sell_msg").empty();
            $("#sell_msg").html("{% trans '价格不能为空' %}");
            return;
        }
        // 判断是否大于当前
        if (!$("#sell_count").val()||$("#sell_count").val() <= 0)
        {
            $("#sell_msg").empty();
            $("#sell_msg").html("{% trans '卖出数量不对' %}");
            return;
        }

        var count = $("#sell_count").val()
        var market_key = g_coin0 + "2" + g_coin1
        var min_count = g_markets[market_key].min_sell_count
        if (count < min_count)
        {
            msg_tips("{% trans '最低卖出数量为' %}: <b class='red'>" +min_count+ "</b> {% trans '请修改后重试' %}", 3000);
            return
        }
        bootbox_sell()
    }

    function bootbox_sell()
    {
        var sell_price = $("#sell_price").val()
        var sell_count = $("#sell_count").val()
        var sell_amount = $("#sell_use_amount").val()
        sell_amount = Calculate.CommaFormattedOnly(sell_amount)
        var message = "{% trans '卖出价格' %}:<b class=red>" + sell_price + "</b>, {% trans '卖出数量' %}:<b class=red>" + sell_count + "</b>,  {% trans '卖出总价' %}:<b class=red>" + sell_amount + "</b>"
        bootbox.confirm({
            title: "{% trans '卖出确认'%}",
            message: message,
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> {% trans "取消卖出" %}'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> {% trans "确认卖出" %}'
                }
            },
            callback: function (result) {
                if (result == true)
                {
                    verify_msm_sell()
                }
                //console.log('This was logged in the callback: ' + result);
            }
        });

    }

    function verify_msm_sell()
    {
        // 检查权限,如果成功就发送
        verify_msm('sell', sell_verify_callback)
    }

    function sell_verify_callback(result)
    {
        if (result)
        {
            send_sell()
        }
    }

    function send_sell()
    {
        //发送数据
        //console.log("sell : " + $("#sell_form").serialize())
        var userid = $("#userid").val();
        $.post("/btc/sell",
        $("#sell_form").serialize(),
        function(data){
            var result = data.result
            if (result == true)
            {
                $("#sell_msg").empty();
                $("#sell_msg").html("{% trans '操作成功' %}");
                msg_tips("<b>{% trans '操作成功' %}</b>", 3000);
                $("#sell_count").empty();
                get_sell_amount();
                get_order_list();
                get_order_history();
            }
            else
            {
                $("#sell_msg").empty();
                msg_tips("<b>{% trans '操作失败' %}</b>", 3000);
                $("#sell_msg").html("{% trans '操作失败' %}");
            }
        });
        $("#sell_count").val(0);
    }

    // 卖出 market
    function on_sell_market_click()
    {
        if (!$("#sell_market_count").val()||$("#sell_market_count").val() <= 0)
        {
            msg_tips("{% trans '卖出数量不对' %}", 3000);
            return;
        }

        var sell_amount = $("#sell_market_count").val()
        var total = $("#sell_amount").html()
        if (total < sell_amount)
        {
            msg_tips("{% trans '卖出数量大于拥有数' %}", 3000);
            return
        }

        var count = $("#sell_market_count").val()
        var market_key = g_coin0 + "2" + g_coin1
        var min_count = g_markets[market_key].min_sell_count
        if (count < min_count)
        {
            msg_tips("{% trans '最低卖出数量为' %}: <b class='red'>" +min_count+ "</b> {% trans '请修改后重试' %}", 3000);
            return
        }

        bootbox_sell_market()
    }

    function bootbox_sell_market()
    {
        var sell_count = $("#sell_market_count").val()
        var message = " {% trans '卖出数量' %}:<b class=red>" + sell_count +"</b>"
        bootbox.confirm({
            title: "{% trans '市价卖出确认'%}",
            message: message,
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> {% trans "取消卖出" %}'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> {% trans "确认卖出" %}'
                }
            },
            callback: function (result) {
                if (result == true)
                {
                    verify_msm_sell_market()
                }
                //console.log('This was logged in the callback: ' + result);
            }
        });
    }

    function verify_msm_sell_market()
    {
        // 检查权限,如果成功就发送
        verify_msm('sell', sell_market_verify_callback)
    }

    function sell_market_verify_callback(result)
    {
        if (result)
        {
            send_market_sell()
        }
    }

    function send_market_sell()
    {
        //发送数据
        //console.log("sell : " + $("#sell_market_form").serialize())
        var userid = $("#userid").val();
        $.post("/btc/sell",
        $("#sell_market_form").serialize(),
        function(data){
            if (data =="True")
            {
                msg_tips("<b>{% trans '操作成功' %}</b>", 3000);
                get_sell_amount();
                get_order_list();
                get_order_history();
            }
            else
            {
                msg_tips("{% trans '操作失败' %}", 3000);
            }
        });
        $("#sell_count").val(0);
    }

    template.defaults.imports.dateFormat=function(str){
        return data_format(str);
    }

    template.defaults.imports.log=console.log

    function get_order_list_not_login()
    {
        var data = {
            coin0: g_coin0,
            coin1: g_coin1,
            coin0_info: g_coin_info[g_coin0],
            coin1_info: g_coin_info[g_coin1],
        }
        var html = template('temp_order_not_login' , data);
        document.getElementById('order_list').innerHTML = html;
        init_middle_collapse()
    }

    function get_order_list()
    {
        //console.log("get order list ")
        if (!g_auth)
        {
            get_order_list_not_login()
            return
        }
        //console.log("get order list ")
        $.post("/btc/get_order_list",
        {coin_type: g_coin0, use_coin_type: g_coin1},
        function(data){
            var jsonobj = data
            //onsole.log("getorder "  + JSON.stringify(jsonobj))
            var data = {
                coin0: g_coin0,
                coin1: g_coin1,
                coin0_info: g_coin_info[g_coin0],
                coin1_info: g_coin_info[g_coin1],
                jsonobj: jsonobj.reverse(),
            }

            var html = template('temp_order', data);
            document.getElementById('order_list').innerHTML = html;
        });
    }

    // 取order history列表
    function get_order_history()
    {
        if (!g_auth)
        {
            return
        }
        //console.log("g_coin0 "  + g_coin0)
        $.post("/btc/get_order_history",
        {coin_type: g_coin0, use_coin_type: g_coin1},
        function(data){
            jsonobj = data
            var data = {
                coin0_info: g_coin_info[g_coin0],
                coin1_info: g_coin_info[g_coin1],
                jsonobj: jsonobj.reverse(),
            }
            var html = template('temp_order_history', data);
            document.getElementById('history_order').innerHTML = html;
        });
    }

    function get_balances()
    {
        //console.log("get balances "  + g_auth)
        if (!g_auth)
        {
            return
        }
        // var userid = $("#userid").val();
        $.post("/btc/get_balances",
        {},
        function(data){
            //console.log("balances "  + JSON.stringify(data))
            var data = {
                jsonobj: data,
                coin_info: g_coin_info
            }
            var html = template('temp_balances', data);
            document.getElementById('balances').innerHTML = html;
        });
    }

    // 合并价格相等的
    function merge_depths(jsonobj, deep)
    {
        var arr =new Array()
        //obj = new Object()
        var last_price = 0
        var last_count = 0
        var last_cnt = 0
        var cnt  = 0
        for(i = 0 ;i < jsonobj.length; i ++ )
        {
            var price = jsonobj[i].price;
            var count = jsonobj[i].count;
            cnt += count
            if (price == last_price)
            {
                last_count += count
                continue
            }
            else
            {
                if (last_price != 0)
                {
                    obj = new Object()
                    obj.price = last_price
                    obj.count = last_count
                    obj.depth = last_cnt
                    arr.push(obj)
                }
                last_price = price
                last_count = count
                last_cnt = cnt
            }
        }
        if (last_price != 0)
        {
            obj = new Object()
            obj.price = last_price
            obj.count = last_count
            obj.depth = last_cnt
            arr.push(obj)
        }
        //总额
        //    console.log("jsonobj "  + JSON.stringify(jsonobj))
        //    console.log("array "  + JSON.stringify(arr))
        return arr
    }

    // 取all order列表
    function get_all_order()
    {
        get_all_order_type(g_coin0, g_coin1, "sell", "#s");
        get_all_order_type(g_coin0, g_coin1, "buy", "#b");
    }

    function clear_depth(show_id, len)
    {
        for(i = len ;i < 20; i ++ )
        {
            var keyprice = show_id+i+"p";
            var keycount = show_id+i+"c";
            var keyvolume = show_id+i+"v";
            var keyvolume_bg = show_id+i+"vw";
            var keydepth = show_id+i+"d";
            $(keyprice).html("-");
            $(keycount).html("-");
            $(keyvolume).html("-");
            $(keydepth).html("-");
            $(keyvolume_bg).attr("style","width:0px;");
        }
    }

    function get_all_order_type(coin_type, use_coin_type, order_type, show_id )
    {
        $.post("/btc/get_all_order",
        {coin_type: coin_type, use_coin_type : use_coin_type, order_type : order_type},
        function(jsonobj){
            var tofixed_price = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
            var tofixed_count = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            var tofixed_depth_amount = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_depth_amount)
            jsonobj = merge_depths(jsonobj, 1)
            //order_list(order_type, jsonobj)
            len = jsonobj.length
            if (len > 21)
            {
                len = 21
            }
            //if (len > 5)
            //    len = 5
            clear_depth(show_id, len)
            if (len == 0)
            {
                return
            }

            // 百分比 bi an 是2ge币是100%
            max = jsonobj[len-1].depth
            for(i = 0 ;i < len; i ++ )
            {
                var price = jsonobj[i].price;
                var count = jsonobj[i].count;
                var depth = jsonobj[i].depth;
                volume = count * price

                var keyprice = show_id+i+"p";
                var keyprice_cny = show_id+i+"p_cny";
                var keycount = show_id+i+"c";
                var keyvolume = show_id+i+"v";
                var keyvolume_bg = show_id+i+"vw";
                var keydepth = show_id+i+"d";
                var keyprice_icon = show_id+i+"icon";
                d = depth * 100 / max
                //price_cny = price * 6.6
                //console.log("max " +  max + " depth " + depth)
                //var price_icon = get_coin_icon(use_coin_type)
                //$(keyprice_icon).html(price_icon);
                $(keyprice).html(price.toFixed(tofixed_price));
                //$(keyprice_cny).html("￥"+price_cny.toFixed(tofixed_price));
                $(keycount).html(count.toFixed(tofixed_count));
                $(keyvolume).html(volume.toFixed(tofixed_count));
                $(keydepth).html(depth.toFixed(tofixed_depth_amount));
                $(keyvolume_bg).attr("style","width:"+(2.80*d)+"px;");
            }

            update_curr_price();
        });
    }

    //
    function update_curr_price()
    {
        var sell_price = $("#s0p").html();
        var buy_price = $("#b0p").html();
        if (buy_price == "-" || sell_price == "-")
        {
            return
        }
        //alert("sell " +sell_price)
        //alert(buy_price)
        var price = (Number(sell_price) + Number(buy_price)) / 2
        var curr_price  = $("#curr_price").html();
        var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
        price = floor_number(price, tofixed1)

        if (price == curr_price)
        {
            return
        }
        $("#curr_price").html(price);
        var coin_price = price * g_ExRate
        coin_price = floor_number(coin_price, tofixed1)

        $("#curr_price").html(Calculate.CommaFormattedOnly(price));
        //$("#cur_coin_price").html(coin_price);
        if  (price > curr_price)
        {
            $("#curr_price").attr("class", "magenta");
            $("#curr_price_icon").attr("class", "magenta");
            $("#curr_price_arrow").attr("class", "fa fa-long-arrow-up magenta");
        }
        else
        {
            $("#curr_price").attr("class", "green");
            $("#curr_price_icon").attr("class", "green");
            $("#curr_price_arrow").attr("class", "fa fa-long-arrow-down green");
        }
    }

    // 取消order
    function on_cancel_order(e)
    {
        //var orderid = e.value;
        //e.preventDefault();
        var orderid = e.getAttribute("data-id");
        //alert(orderid);
        id = "#block_" + orderid
        //console.log("go cancel %s " , id)
        $(id).toggle('fade')
        $.post("/btc/delete_order",
        {orderid: orderid},
        function(data){
            //console.log("cancel return "  + JSON.stringify(data))
            //alert(data);
            get_order_list();
            get_buy_amount();
            get_sell_amount();
            //get_all_order_list();
        });
    }

    // 点击数字和价格
    function on_all_order_click(e)
    {
        var price = $(e).find(".price")
        price = Number(price.html())
        if (!(price > 0))
        {
            return
        }
        click_change_price(price)
    }

    function on_curr_price_click(e)
    {
        price = Number($("#curr_price").html())
        if (!(price > 0))
        {
            return
        }
        click_change_price(price)
    }

    function click_change_price(price)
    {
        $("#buy_price").val(price)
        on_buy_price_change();
        $("#sell_price").val(price)
        on_sell_price_change();
    }

    function get_last_trade()
    {
        //console.log("get_last_trade")
        $.post("/btc/get_last_trade",
        {coin_type: g_coin0, use_coin_type: g_coin1},
        function(jsonobj){
            //onsole.log("get_last_trade return" + jsonobj.length)
            var tdata = {
                price: "{% trans '价格' %}",
                num: "{% trans '数量' %}",
                times: "{% trans '时间' %}",
                title: "{% trans '最新成交' %}",
            }
            var data = {
                coin0: g_coin0,
                coin1: g_coin1,
                coin0_info: g_coin_info[g_coin0],
                coin1_info: g_coin_info[g_coin1],
                jsonobj: jsonobj,
                tdata: tdata,
            }
            var html = template("temp_last_trade", data);
            document.getElementById("last_trade").innerHTML = html;

            var json2=new Array()
            var len = data.jsonobj.length
            if (len > 20){
                len = 20
            }
            for(i = 0 ;i < len; i ++ ){
                var info = data.jsonobj[i]
                json2.push(info)
            }
            data.jsonobj = json2
            var html = template("temp_last_trade", data);
            document.getElementById("last_trade2").innerHTML = html;
        });
    }

    // 取余额
    function get_amount(coin_type, show_id)
    {
        if (!g_auth)
        {
            return
        }
        var userid = $("#userid").val();
        var amount = 0;
        var freeze = 0;
        $.post("/btc/get_amount",
        {coin_type: coin_type, userid : userid},
        function(data){
            amount = data['amount']
            if (coin_type == g_coin0)
            {
                tofixed = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_count)
            }
            else
            {
                tofixed = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
            }
            old_amount = $(show_id).html();
            new_amount = floor_number(amount, tofixed)
            //console.log("%r %r %r", old_amount, new_amount, tofixed)
            if (old_amount != new_amount)
            {
                $(show_id).empty();
                $(show_id).html(new_amount);
            }
        })
    }

    function set_timer()
    {
        var last_trade = setInterval(get_last_trade, 10000);
        var all_order = setInterval(get_all_order, 1000);
        var market = setInterval(get_curr_market, 4000);
        var market = setInterval(get_market_left, 4000);
        var self_order = setInterval(get_order_list, 10000);
        var buy_balance = setInterval(get_buy_amount, 2000);
        var sell_balance = setInterval(get_sell_amount, 2000);
    }

    // init 深度
    function init_depths()
    {
        var tdata = {
            price: "{% trans '价格' %}",
            num: "{% trans '数量' %}",
            amount: "{% trans '金额' %}",
            depth: "{% trans '深度' %}",
        }
        var data = {
            coin0: g_coin0,
            coin1: g_coin1,
            coin0_info: g_coin_info[g_coin0],
            coin1_info: g_coin_info[g_coin1],
            tdata : tdata
        }
        var html = template("temp_depths", data);
        document.getElementById("depths").innerHTML = html;
    }

    // init markets
    function init_markets()
    {
        var data = {
            markets: g_markets
        };
        var key = g_coin0 + "2" + g_coin1
        for (i in data.markets) {
            info = data.markets[i]
            if (info.key == key){
                info.cur = true;
                } else {
                info.cur = false;
            }
        }
        //console.log("markets %s " , data.markets.length)
        var html = template("tmp_markets", data);
        document.getElementById("markets").innerHTML = html;
        var html = template("tmp_markets_left", data);
        document.getElementById("markets_left").innerHTML = html;

    }

    //
    function init_curr_markets()
    {
        var data = {
            coin0: g_coin0,
            coin1: g_coin1,
            coin0_info: g_coin_info[g_coin0],
            coin1_info: g_coin_info[g_coin1],
        };
        var html = template("temp_curr_market", data);
        document.getElementById("curr_market").innerHTML = html;
    }

    function init_trade_form(type1)
    {
        var data = {
            coin0: g_coin0,
            coin1: g_coin1,
            coin0_info: g_coin_info[g_coin0],
            coin1_info: g_coin_info[g_coin1]
        };
        if (type1 == 'limit')
        {
            var html = template("temp_buy", data);
            document.getElementById("trade_buy").innerHTML = html;
            var html = template("temp_sell", data);
            document.getElementById("trade_sell").innerHTML = html;
            $("#trade_market").removeClass("cur")
            $("#trade_limit").addClass("cur");
            init_limit_from_ready()
        }
        else
        {
            $("#trade_market").addClass("cur");
            $("#trade_limit").removeClass("cur")
            var html = template("temp_buy_market", data);
            document.getElementById("trade_buy").innerHTML = html;
            var html = template("temp_sell_market", data);
            document.getElementById("trade_sell").innerHTML = html;
            init_market_from_ready()
        }
    }


    function get_curr_market()
    {
        $.post("/btc/get_curr_market", {}, function(jsonobj){
            for (i = 0; i < jsonobj.length; i++)
            {
                var info = jsonobj[i];
                var key = info.coin_type + "2" + info.use_coin_type;
                //            console.log("====key "  + key)
                var market = g_markets[key];
                if (market == undefined || market.active == false) {
                    continue;
                }

                var price_key = "#" + key +"_market_curr_price";
                var percent_key ="#" + key +"_percent";
                var arrow_key ="#" + key +"_arrow";

                var tofixed = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
                var curr = floor_number(info.curr, tofixed)

                $(price_key).html(curr);

                var percent = 0
                if (info.curr != info.open)
                {
                    percent = (info.curr - info.open) * 100 / info.open
                    tofixed = 2
                    percent = floor_number(percent, tofixed)
                }

                if (percent != 0)
                {
                    if (percent > 0)
                    {
                        $(percent_key).html("+"+percent+"%");
                        $(percent_key).attr("class", "red");
                    }
                    else
                    {
                        $(percent_key).html(percent+"%");
                        $(percent_key).attr("class", "green");
                    }
                }
                else
                {
                    $(percent_key).attr("class", "green");
                    $(percent_key).html("+0.00%");
                }

                if (info.arrow == 0)
                {
                    $(arrow_key).attr("class", "");
                }
                if (info.arrow == 1)
                {
                    $(arrow_key).attr("class", "fa fa-arrow-up red");
                }
                if (info.arrow == 2)
                {
                    $(arrow_key).attr("class", "fa fa-arrow-down greed");
                }

                if (info.coin_type == g_coin0 && info.use_coin_type == g_coin1)
                {
                    set_curr_price(info, percent)
                }
            }
        })
    }

    function set_curr_price(info, percent)
    {
        var curr_price  = $("#curr_price").html();
        var tofixed0 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
        var tofixed1 = coin_tofixed(g_coin0, g_coin1, coin_tofixed_type_price)
        curr = info.curr.toFixed(tofixed1)
        volume = info.volume.toFixed(tofixed0)
        high= info.high.toFixed(tofixed1)
        low = info.low.toFixed(tofixed1)
        coin_curr = curr * g_ExRate
        coin_curr = coin_curr.toFixed(tofixed1)
        if (curr_price == 0)
        {
            $("#curr_price").html(curr)
        }

        $("#last_price").html(Calculate.CommaFormattedOnly(curr) )
        $("#coin_last_price").html(coin_curr)
        $("#last_high_price").html(Calculate.CommaFormattedOnly(high))
        $("#last_low_price").html(Calculate.CommaFormattedOnly(low))
        $("#day_volume").html(Calculate.CommaFormattedOnly(volume))
        var percent_key = "#day_rose"
        var arrow_key = "#curr_arrow"
        if (percent != 0)
        {
            if (percent > 0)
            {
                $(percent_key).html("+"+percent+"%");
                $(percent_key).attr("class", "red");
            }
            else
            {
                $(percent_key).html(percent+"%");
                $(percent_key).attr("class", "green");
            }
        }
        else
        {
            $(percent_key).html("+0.00%");
        }

        if (info.arrow == 0)
        {
            $(arrow_key).attr("class", "");
        }
        if (info.arrow == 1)
        {
            $(arrow_key).attr("class", "fa fa-arrow-up red");
        }
        if (info.arrow == 2)
        {
            $(arrow_key).attr("class", "fa fa-arrow-down greed");
        }
    }
</script>
